import axios from 'axios';
import { Message } from 'element-ui';
import { getToken, removeToken, setExpire } from '@/utils';

// export const base = 'http://121.43.57.185:8088'
// export const base = 'http://59.52.188.147:8088'

// eslint-disable-next-line
export const base = SERVICE_BASIC;

let hasMessage = false;
const instance = axios.create({
  timeout: 3 * 60 * 1000,
  baseURL: base
});

instance.interceptors.request.use(
  config => {
    config.headers.token = getToken();
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {
      return response;
    }
    // 2xx
    const { code, message } = response.data || {};
    if (code !== 200) {
      if ((code === 401 || code === 406) && !hasMessage) {
        removeToken();
        setTimeout(() => {
          location.reload();
        }, 20);
        // hasMessage = true
        // return MessageBox.confirm(message || '登录超时，请重新登录', '温馨提示')
        //   .then(() => {
        //     hasMessage = false
        //     removeToken()
        //     setTimeout(() => {
        //       location.reload()
        //     }, 20)
        //   })
        //   .catch(() => {
        //     hasMessage = false
        //   })
      }
      if (!hasMessage) {
        hasMessage = true;
        Message.error({
          message,
          onClose() {
            hasMessage = false;
          }
        });
      }
      return Promise.reject(new Error(message));
    }
    setExpire(Date.now());
    return response.data;
  },
  error => {
    // >2xx
    if (!hasMessage) {
      hasMessage = true;
      Message.error({
        message: error && error.message ? error.message : '系统异常',
        onClose() {
          hasMessage = false;
        }
      });
    }
    return Promise.reject(error);
  }
);

export default instance;
